//
//  InvesmentSureViewController.m
//  SP2P
//
//  Created by Eternal on 2017/8/23.
//  Copyright © 2017年 EIMS. All rights reserved.
//

#import "InvesmentSureViewController.h"
#import "UILabel+attributeTextAction.h"
#import "VerifyMobileViewController.h"
@interface InvesmentSureViewController ()<HTTPClientDelegate,UIAlertViewDelegate>
{
    UIView      *_verifyPwdSuccessView;
    UIView      *_inputErrorView;
    UILabel     *_errorNumLabel;
    NSInteger   _errorNum;
}
@property (weak, nonatomic) IBOutlet UILabel *productNameLab;
@property (weak, nonatomic) IBOutlet UILabel *productNameValueLab;
@property (weak, nonatomic) IBOutlet UILabel *productTimeLab;
@property (weak, nonatomic) IBOutlet UILabel *productTimeValueLab;
@property (weak, nonatomic) IBOutlet UILabel *availableMoneyLab;
@property (weak, nonatomic) IBOutlet UILabel *availableMoneyValueLab;
@property (weak, nonatomic) IBOutlet UILabel *investMoneyLab;
@property (weak, nonatomic) IBOutlet UILabel *investMoneyValueLab;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;
@property (weak, nonatomic) IBOutlet UILabel *textLab;

@property (weak, nonatomic) IBOutlet ClickButton *sureBtn;
@property (nonatomic, strong) NSArray        *titleArray;
@property (nonatomic, assign) BOOL           isSecurity;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, copy  ) NSString       *pwdStr;
@property (nonatomic, strong) UIView         *setView;
@property (nonatomic, strong) UIView         *backView;
@property (nonatomic, strong) UIView         *keyBoardView;
@property (nonatomic, strong) UIView         *enterView;
@property (nonatomic, strong) UIButton       *cancelButton;
@property (nonatomic, strong) UILabel        *operationNameLabel;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, strong) NetWorkClient *requestClient;
@end

@implementation InvesmentSureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    
    [self initView];
    [self loadInputView];
    [self loadInputErrorView];
    
}
#pragma mark - initView
- (void)initView{
    [self initNavBarTitle:@"投资确认" andLeftItemName:@"返回" andRightItemName:@""];
    self.productNameLab.font = KFontSize(12);
    self.productNameValueLab.font = KFontSize(12);
    self.productTimeLab.font = KFontSize(12);
    self.productTimeValueLab.font = KFontSize(12);
    self.availableMoneyLab.font = KFontSize(12);
    self.availableMoneyValueLab.font = KFontSize(12);
    self.investMoneyLab.font = KFontSize(12);
    self.investMoneyValueLab.font = KFontSize(12);
    self.sureBtn.titleLabel.font = KFontSize(12);
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5;
    self.textLab.font = KFontSize(10);
    
    NSString *mindStr = [NSString stringWithFormat:@"本人已阅读《借款协议书(%@)》,并已完全理解、接受和同意签署上述文件的全部内容.本人的投资决策完全基于本人的独立自主判断做出,并自愿承担投资该项目所产生的相关风险和后果.",self.productName];
    
    CGFloat mindHeight = [MyTools getSizeOfString:mindStr maxWidth:MSWIDTH - 20 maxHeight:1000 withFontSize:10].height;
    CGRect frame = self.textLab.frame;
    if (IS_iPhone5) {
        frame.size.height = mindHeight+KAdaptNum(30);
    }else if (IS_iPhone6){
        
        frame.size.height = mindHeight+KAdaptNum(2);
    }else{
        frame.size.height = mindHeight-KAdaptNum(3);
    }
    
    self.textLab.frame = frame;
    //通过字符串标记
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:mindStr];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, attributedString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(5, 12)];
    self.textLab.attributedText = attributedString;
    [self.textLab addAttributeActionWithStrings:@[[NSString stringWithFormat:@"《借款协议书(%@)》",self.productName]] tapTargetAction:^(NSString *string, NSRange range, NSInteger index) {
        NSLog(@"点击字符串:%@ 范围在%@，第%ld个",string,NSStringFromRange(range),index+1);
    }];

}
- (void)loadInputView {
    _setView = [UIView viewWithFrame:RECTMAKE(0, MSHIGHT, MSWIDTH, MSHIGHT) backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.3] superview:AppDelegateInstance.window];
    _setView.hidden = YES;
    
    _backView = [UIView viewWithFrame:RECTMAKE(0, GetHeight(_setView) - KAdaptNum(320), MSWIDTH, KAdaptNum(320)) backgroundColor:[UIColor whiteColor] superview:_setView];
    
    _cancelButton = [UIButton buttonWithFrame:RECTMAKE(0, 0, KAdaptNum(40), KAdaptNum(40)) backgroundColor:nil title:@"" titleColor:nil titleFont:0 target:self action:@selector(cancelButtonClick) superview:_backView];
    [_cancelButton setImage:[UIImage imageNamed:@"SetPayPwd_Cancel"] forState:UIControlStateNormal];
    
    _operationNameLabel = [UILabel labelWithFrame:RECTMAKE(10, 0, MSWIDTH - 20, KAdaptNum(40)) text:@"输入交易密码" textColor:KBlackColor textFont:16 fitWidth:NO superview:_backView];
    _operationNameLabel.textAlignment = NSTextAlignmentCenter;
    
    [UIView viewWithFrame:RECTMAKE(0, KAdaptNum(40)-1, MSWIDTH, 1) backgroundColor:KlayerBorder superview:_backView];
    
    _keyBoardView = [UIView viewWithFrame:RECTMAKE(0, KAdaptNum(40), MSWIDTH, GetHeight(_backView) - KAdaptNum(40)) backgroundColor:[UIColor whiteColor] superview:_backView];
    
    
    _enterView = [UIView viewWithFrame:RECTMAKE(10, KAdaptNum(20), MSWIDTH - 20, KAdaptNum(40)) backgroundColor:[UIColor whiteColor] superview:_keyBoardView];
    _enterView.layer.cornerRadius = 3.0f;
    _enterView.layer.borderColor = KlayerBorder.CGColor;
    _enterView.layer.borderWidth = 1.0f;
    
    for (NSInteger i=0; i < 6; i++) {
        UITextField *textField = [UITextField textFieldWithFrame:RECTMAKE((GetWidth(_enterView)/6)*i, 0, GetWidth(_enterView)/6, GetHeight(_enterView)) delegate:self text:@"" textColor:KBlackColor textFont:16 placeholder:@"" superview:_enterView];
        textField.userInteractionEnabled = NO;
        textField.tag = 200 + i;
        textField.textAlignment = NSTextAlignmentCenter;
        
        if (i < 5) {
            [UIView viewWithFrame:RECTMAKE(((GetWidth(_enterView))/6)*(i+1), 0, 1, GetHeight(_enterView)) backgroundColor:KlayerBorder superview:_enterView];
        }
    }
    
    for (NSInteger i=0; i < _titleArray.count; i++) {
        double w = MSWIDTH/3;
        double h = KAdaptNum(50);
        double x = w * (i%3);
        double y = GetMaxY(_enterView) + KAdaptNum(20) + h * (i/3);
        
        UIButton *button = [UIButton buttonWithFrame:RECTMAKE(x, y, w, h) backgroundColor:nil title:_titleArray[i] titleColor:KBlackColor titleFont:16 target:self action:@selector(numButtomClick:) superview:_keyBoardView];
        button.titleLabel.font = KFontBoldSize(16);
        button.tag = 100 + i;
        if (i == 9) {
            [button setTitle:@"" forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"ModifyDealPwd_Logo"] forState:UIControlStateNormal];
        }else if (i == 11) {
            [button setTitle:@"" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ModifyDealPwd_Delete"] forState:UIControlStateNormal];
        }
    }
    
    for (NSInteger i=0; i < 5; i++) {
        [UIView viewWithFrame:RECTMAKE(0, GetMaxY(_enterView) + KAdaptNum(20) + KAdaptNum(50) * i, MSWIDTH, 1) backgroundColor:KlayerBorder superview:_keyBoardView];
    }
    for (NSInteger i=0; i < 4; i++) {
        [UIView viewWithFrame:RECTMAKE(MSWIDTH/3*(i+1), GetMaxY(_enterView) + KAdaptNum(20), 1, KAdaptNum(50)*4) backgroundColor:KlayerBorder superview:_keyBoardView];
    }
}

- (void)loadVerifyPasswordSuccessView {
    _verifyPwdSuccessView = [UIView viewWithFrame:RECTMAKE(0, KAdaptNum(40), MSWIDTH, GetHeight(_backView)-KAdaptNum(40)) backgroundColor:[UIColor whiteColor] superview:_backView];
    
    UIImageView *successImageView = [UIImageView imageViewWithFrame:RECTMAKE((MSWIDTH - 50)/2, 60, 50, 50) imageFile:@"VerifyPwdSuccess" superview:_verifyPwdSuccessView];
    
    UILabel *label = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(successImageView) + 10, MSWIDTH - 20, KAdaptNum(20)) text:@"验证成功" textColor:GreenColor textFont:14 fitWidth:YES superview:_verifyPwdSuccessView];
    label.textAlignment = NSTextAlignmentCenter;
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_verifyPwdSuccessView removeFromSuperview];
        [self cancelButtonClick];
        [self tenderRequest];
    });
    
}

- (void)loadInputErrorView {
    
    _inputErrorView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT) backgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.3] superview:AppDelegateInstance.window];
    _inputErrorView.hidden = YES;
    
    UIView *errorBackView = [UIView viewWithFrame:RECTMAKE(35, (MSHIGHT - KAdaptNum(320)) + (KAdaptNum(320) - KAdaptNum(120))/2, MSWIDTH - 70, KAdaptNum(120)) backgroundColor:[UIColor whiteColor] superview:_inputErrorView];
    errorBackView.layer.cornerRadius = KAdaptNum(5.0);
    
    _errorNumLabel = [UILabel labelWithFrame:RECTMAKE(20, 0, GetWidth(errorBackView) - 40, KAdaptNum(120) - KAdaptNum(36) - 20) text:[NSString stringWithFormat:@"原交易密码不正确"] textColor:KBlackColor textFont:14 fitWidth:NO superview:errorBackView];
    _errorNumLabel.textAlignment = NSTextAlignmentCenter;
    _errorNumLabel.numberOfLines = 0;
    
    [UIView viewWithFrame:RECTMAKE(0, GetHeight(errorBackView) - KAdaptNum(40) - 1, GetWidth(errorBackView), 1) backgroundColor:KlayerBorder superview:errorBackView];
    
    [UIView viewWithFrame:RECTMAKE(GetWidth(errorBackView)/2, GetHeight(errorBackView) - KAdaptNum(40) - 1, 1, KAdaptNum(40)) backgroundColor:KlayerBorder superview:errorBackView];
    
    UIButton *inputButton = [UIButton buttonWithFrame:RECTMAKE(20, GetHeight(errorBackView) - KAdaptNum(40), (GetWidth(errorBackView)-60)/2, KAdaptNum(40)) backgroundColor:nil title:@"重新输入" titleColor:KBlackColor titleFont:14 target:self action:@selector(inputButtonClick) superview:errorBackView];
    
    UIButton *forgetButton = [UIButton buttonWithFrame:RECTMAKE(GetMaxX(inputButton) + 20, GetMinY(inputButton), (GetWidth(errorBackView)-60)/2, GetHeight(inputButton)) backgroundColor:nil title:@"找回密码" titleColor:BluewordColor titleFont:14 target:self action:@selector(forgetPwdButtonClick) superview:errorBackView];
    forgetButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    
}

#pragma mark - initData
- (void)initData{
    self.productNameValueLab.text = self.productName;
    self.productTimeValueLab.text = [NSString stringWithFormat:@"%@个月",self.monthStr];
    self.availableMoneyValueLab.text = [NSString stringWithFormat:@"%.2f元",self.balance];
    self.investMoneyValueLab.text = [NSString stringWithFormat:@"%@元",self.InvestAmountStr];
    _dataArr = [NSMutableArray array];
    _isSecurity = YES;
    _pwdStr = @"";
    _titleArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"L",@"0",@"X"];
}
- (void)tenderRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍候..."];
        return;
    }
    _requestType = 1;
    [SVProgressHUD showWithStatus:@"开始投标..." maskType:SVProgressHUDMaskTypeGradient];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"508" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    [parameters setObject:_signStr forKey:@"planId"];
    
    NSString *password = [NSString encrypt3DES:_pwdStr key:DESkey];
    [parameters setObject:password forKey:@"dealpwd"];
    [parameters setObject:_InvestAmountStr forKey:@"investAmount"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
    
}

- (void)verifyTradePasswordRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍候..."];
        return;
    }
    _requestType = 2;
    
    [SVProgressHUD showWithStatus:@"正在验证交易密码..." maskType:SVProgressHUDMaskTypeGradient];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"510" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    NSString *password = [NSString encrypt3DES:_pwdStr key:DESkey];
    [parameters setObject:password forKey:@"currentdealpwd"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)startRequest {
    _isLoading = YES;
}
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    [SVProgressHUD dismiss];
    _isLoading = NO;
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"--%@",dics);
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            _pwdStr = @"";
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            });

            }else if(_requestType == 2)
            {
             
                [self loadVerifyPasswordSuccessView];
           
            }
            }
           else {
        if (_requestType == 2) {
            _errorNum ++;
            [self reloadErrorNum:_errorNum];
        }else {
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
        }
    }
}

- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [SVProgressHUD dismiss];
}

- (void) networkError {
    _isLoading = NO;
    [SVProgressHUD dismiss];
}


#pragma mark -Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    
    if (alertView.tag==12 && buttonIndex==0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sqbBalanceChange" object:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
    }else if (alertView.tag == 13 && buttonIndex == 0){
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}



#pragma mark - Action

- (void)back {
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"确认要取消该笔投资吗?" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil] ;
    alert.tag = 13;
    [alert show] ;
}

- (IBAction)clickSelect:(id)sender {
    self.selectBtn.hidden = NO;
}
- (IBAction)clickUnselect:(id)sender {
    self.selectBtn.hidden = YES;
}

- (IBAction)clickSure:(id)sender {
    if (!self.selectBtn.hidden) {
        
        [self showInputView];
        
    }else{
       
        [SVProgressHUD showErrorWithStatus:@"请勾选上方借款协议书!"];
    }
}
- (void)numButtomClick:(UIButton *)button {
    
    NSInteger index = button.tag - 100;
    if (index == 11) {
        if (_dataArr.count > 0) {
            [_dataArr removeLastObject];
        }
    }else if (index == 9) {
        
    }else {
        if (_dataArr.count < 6) {
            [_dataArr addObject:_titleArray[index]];
        }
        if (_dataArr.count >= 6) {
            [self inputSuccess];
        }
    }
    [self reloadEnterView];
}

- (void)inputSuccess {
    
    _pwdStr = [_dataArr componentsJoinedByString:@""];
    [self verifyTradePasswordRequest];
}

- (void)reloadEnterView {
    for (UIView *subView in _enterView.subviews) {
        if ([subView isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)subView;
            textField.text = @"";
        }
    }
    if (_dataArr.count > 0) {
        for (NSInteger i=0; i < _dataArr.count; i++) {
            UITextField *textField = [_enterView viewWithTag:200 + i];
            if (_isSecurity) {
                textField.text = @"●";
            }else {
                textField.text = _dataArr[i];
            }
        }
    }
}
- (void)cancelButtonClick {
    [self hiddenInputView];
    
}
- (void)showInputView {
    
    _setView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _setView.frame = RECTMAKE(0, 0, MSWIDTH, MSHIGHT);
        
    } completion:^(BOOL finished) {
        
        
    }];
}

- (void)hiddenInputView {
    [UIView animateWithDuration:0.3 animations:^{
        _setView.frame = RECTMAKE(0, MSHIGHT, MSWIDTH, MSHIGHT);
        
    } completion:^(BOOL finished) {
        
        [_dataArr removeAllObjects];
        [self reloadEnterView];
        
        _setView.hidden = YES;
        
    }];
}
- (void)inputButtonClick {
    
    [_dataArr removeAllObjects];
    [self reloadEnterView];
    
    [self inputErrorViewHidden];
}

- (void)forgetPwdButtonClick {
    
    _setView.hidden = YES;
    _inputErrorView.hidden = YES;
    _keyBoardView.hidden = NO;
    
    [_dataArr removeAllObjects];
    [self reloadEnterView];
    
    //先验证手机号码
    VerifyMobileViewController *verifyMobile = [[VerifyMobileViewController alloc] init];
    verifyMobile.viewType = ResetDealPassword;
    verifyMobile.naviTitle = @"验证手机号";
    verifyMobile.mobileStr = AppDelegateInstance.userInfo.mobile;
    [self.navigationController pushViewController:verifyMobile animated:YES];
    
}

- (void)reloadErrorNum:(NSInteger)errorNum {
    //_errorNumLabel.text = [NSString stringWithFormat:@"交易密码不正确，您还可以输入%ld次",3-errorNum];
    _errorNumLabel.text = [NSString stringWithFormat:@"原交易密码不正确!"];
    [self inputErrorViewShow];
}

- (void)inputErrorViewShow {
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"交易密码不正确" delegate:self cancelButtonTitle:@"重新输入" otherButtonTitles:@"找回密码", nil];
    //    [alert show];
    //    return;
    _keyBoardView.hidden = YES;
    _inputErrorView.hidden = NO;
    [AppDelegateInstance.window bringSubviewToFront:_inputErrorView];
}

- (void)inputErrorViewHidden {
    _keyBoardView.hidden = NO;
    _inputErrorView.hidden = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
